package com.sangmo.fts.process.inventory.service;

import com.sangmo.boot.framework.common.errors.ServiceException;
import com.sangmo.boot.framework.common.errors.StandardErrors;
import com.sangmo.fts.basic.model.FileUpload;
import com.sangmo.fts.basic.service.FileUploadService;
import com.sangmo.fts.process.inventory.model.IfLadingBill;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class IfLadingBillDocumentService {

    @Autowired
    private IfLadingBillEntityService ifLadingBillEntityService;

    @Autowired
    private FileUploadService fileUploadService;

    public FileUpload createBillApplyDoc(Long ladingBillId, Long fileUploadId) {
        IfLadingBill ladingBill = ifLadingBillEntityService.get(ladingBillId);
        if (IfLadingBill.States.SUBMITTED.equals(ladingBill.getState())) {
            throw new ServiceException(StandardErrors.CLIENT_ERROR.getStatus(), "error.ifLadingBill.upload.commit.disabled");
        }
        ladingBill.setBillApplyDoc(fileUploadId);
        ifLadingBillEntityService.save(ladingBill);
        return create(ladingBillId, fileUploadId, "IfLadingBill.Apply");
    }

    public FileUpload createBillConfirmDoc(Long ladingBillId, Long fileUploadId) {
        IfLadingBill ladingBill = ifLadingBillEntityService.get(ladingBillId);
        if (IfLadingBill.BankAckStates.CONFIRMED.equals(ladingBill.getBankAckState())) {
            throw new ServiceException(StandardErrors.CLIENT_ERROR.getStatus(), "error.ifLadingBill.upload.confirm.disabled");
        }
        ladingBill.setBillConfirmDoc(fileUploadId);
        ifLadingBillEntityService.save(ladingBill);
        return create(ladingBillId, fileUploadId, "IfLadingBill.Confirm");
    }

    public FileUpload createBillReceiptDoc(Long ladingBillId, Long fileUploadId) {
        IfLadingBill ladingBill = ifLadingBillEntityService.get(ladingBillId);
        if (IfLadingBill.StorageAckStates.COMPLETED.equals(ladingBill.getStorageAckState())) {
            throw new ServiceException(StandardErrors.CLIENT_ERROR.getStatus(), "error.ifLadingBill.upload.complete.disabled");
        }
        ladingBill.setBillReceiptDoc(fileUploadId);
        ifLadingBillEntityService.save(ladingBill);
        return create(ladingBillId, fileUploadId, "IfLadingBill.Receipt");
    }

    public FileUpload create(Long LadingBillId, Long fileUploadId, String refType) {
        FileUpload upload = fileUploadService.updateRef(fileUploadId, ""+LadingBillId, refType);
        return upload;
    }

    public void remove(Long ladingBillId) {
        IfLadingBill ifLadingBill = ifLadingBillEntityService.get(ladingBillId);
        fileUploadService.remove(ifLadingBill.getBillApplyDoc());
        ifLadingBill.setBillApplyDoc(null);
        ifLadingBillEntityService.save(ifLadingBill);
    }

}
